package com.cg.service.impl;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cg.common.Constants;
import com.cg.config.MyAlipayConfig;
import com.cg.dao.DmOrderMapper;
import com.cg.dto.DtoEnum;
import com.cg.dto.OrderManagerDto;
import com.cg.entity.DmOrder;
import com.cg.service.DmOrderService;
import com.cg.utils.AliPayUtil;
import com.cg.utils.DateUtil;
import com.cg.vo.OrderManagerVo;
import com.cg.vo.QueryOrderVo;
import com.cg.vo.SeatVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 订单表(DmOrder)表服务实现类
 *
 * @author makejava
 * @since 2023-11-13 09:49:23
 */
@Service("dmOrderService")
@Slf4j
public class DmOrderServiceImpl implements DmOrderService {
    @Resource
    private DmOrderMapper dmOrderMapper;

    @Resource
    private MyAlipayConfig myAlipayConfig;


    @Resource
    private AliPayUtil aliPayUtil;

    //根据订单状态、订单创建时间、关键词(商品名称，订单号，商品编号模糊)
    @Override
    public List<OrderManagerVo> queryOrderList(OrderManagerDto orderManagerDto) {
        //判断时间
        Integer orderTime = orderManagerDto.getOrderTime();
        Date date = null;
        DateFormat format = new SimpleDateFormat("yyyy-DD-mm HH:mm:ss");
        String createTime = "";

        if(orderTime.equals(0)){
            //查询所有
            orderManagerDto.setOrderTime(null);
        }else if(orderTime.equals(1)){
            //计算1年之前的时间
            date = DateUtil.getDate(1, Calendar.YEAR);
            createTime = format.format(date);
        }else{
            //前3个月的
            date = DateUtil.getDate(3,Calendar.MONTH);
            createTime = format.format(date);
        }
        orderManagerDto.setCreateTime(createTime);
        return dmOrderMapper.queryOrderList(orderManagerDto);
    }

    //根据订单号查询订单
    @Override
    public QueryOrderVo queryOrderByOrderNo(String orderNo) {
        QueryOrderVo queryOrderVo = dmOrderMapper.queryOrderByOrderNo(orderNo);
        List<SeatVo> seatVoList = queryOrderVo.getSeatVoList();
        if(seatVoList == null || seatVoList.size() == 0){
            queryOrderVo.setSeatName("");
            queryOrderVo.setSeatCount(0);
            return queryOrderVo;
        }

        queryOrderVo.setSeatCount(seatVoList.size());
        String seatName = "";
        for (SeatVo seatVo : seatVoList) {
            seatName = seatVo.getX()+":"+seatVo.getY()+";";
        }
        //去除最后的逗号
        seatName=seatName.substring(0,seatName.length()-1);
        queryOrderVo.setSeatName(seatName);
        return queryOrderVo;
    }

    //订单支付
    @Override
    public String toPay(String orderNo) throws AlipayApiException {
        //根据订单编号查询支付金额
        QueryWrapper<DmOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderNo",orderNo);
        DmOrder dmOrder = dmOrderMapper.selectOne(queryWrapper);
        if(dmOrder == null){
            //没有此订单
            return DtoEnum.FAIL_ORDER.getMsg();
        }

        //校验订单状态
        if(!dmOrder.getOrderType().equals(Constants.OrderStatus.TOPAY)){
            //订单状态不符合
            return DtoEnum.FAIL_ORDER_STATE.getMsg();
        }

        //去支付
        BigDecimal totalAmount = dmOrder.getTotalAmount();
        String toPay = aliPayUtil.toPay(orderNo, totalAmount.toString());

        return toPay;
    }

    @Override
    public String notify(Map<String, String> params) {
        //参数的校验
        //appId
        String appId = params.get("app_id");
        if(!appId.equals(myAlipayConfig.getAppId())){
            log.info("appId不一致");
            return Constants.AliPayStatus.FAIL;
        }
        //订单校验
        //订单是否存在
        String orderNo = params.get("out_trade_no");
        QueryWrapper<DmOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderNo",orderNo);
        DmOrder dmOrder = dmOrderMapper.selectOne(queryWrapper);
        if(dmOrder == null){
            log.info("订单不存在");
            return Constants.AliPayStatus.FAIL;
        }
        //订单状态是否未支付
        if(!dmOrder.getOrderType().equals(Constants.OrderStatus.TOPAY)){
            log.info("订单已处理");
            return Constants.AliPayStatus.FAIL;
        }

        //订单金额
        String total_amount = params.get("total_amount");
        BigDecimal totalAmount = new BigDecimal(total_amount);
        BigDecimal totalAmountOrder = dmOrder.getTotalAmount();
        if(!(totalAmount.compareTo(totalAmountOrder)==0)){
            log.info("订单金额不符合");
            return Constants.AliPayStatus.FAIL;
        }

        //支付状态
        String trade_status = params.get("trade_status");
        //支付宝交易号
        String trade_no = params.get("trade_no");
        //修改订单
        QueryWrapper<DmOrder> updateQueryWrapper = new QueryWrapper<>();
        updateQueryWrapper.eq("orderNo",orderNo);
        updateQueryWrapper.eq("orderType",Constants.OrderStatus.TOPAY);//未支付
        dmOrder.setUpdatedTime(new Date());//最后修改时间
        dmOrder.setPayType(Constants.PayType.ALIPAY);//支付类型 1、微信支付 2、支付宝支付
        dmOrder.setAliTradeNo(trade_no);//支付宝交易号
        if(trade_status.equals("TRADE_CLOSED")){
            //未付款交易超时关闭，或者支付完成混全额退款
            dmOrder.setOrderType(Constants.OrderStatus.FAIL);//失败
            dmOrderMapper.update(dmOrder,updateQueryWrapper);
            return Constants.AliPayStatus.SUCCESS;
        }

        if(trade_status.equals("TRADE_SUCCESS")){
            //支付交易成功
            dmOrder.setOrderType(Constants.OrderStatus.SUCCESS);//成功
            dmOrderMapper.update(dmOrder,updateQueryWrapper);
            return Constants.AliPayStatus.SUCCESS;
        }

        return Constants.AliPayStatus.SUCCESS;
    }
}
